#!/bin/bash
project=JaXB
if test "${1}" == ""; then
  echo deploy.sh
  echo "Usage: deploy.sh ENV {deploy}"
  echo "Optional second argument == deploy will skip building the project and just deploy"
  echo "   ${project}-assembly/target/${project}-mule-\${1}.tar.gz"
  exit 1
fi

# cwd=${PWD}
echo "PWD = ${PWD}"

workdir="${PWD}"

propertiesPath="${workdir}/${project}-assembly/src/main/filters/${1}.properties"

installdirVar=`grep ^install.dir ${propertiesPath}`
installdirVar=${installdirVar##*=}
installdirVar=${installdirVar/\$\{project.name\}/${project}}
installdirVar=${installdirVar/\$\{env.name\}/${1}}
deployDir=${installdirVar}

tarPath="${workdir}/${project}-assembly/target/${project}-mule-${1}.tar.gz"
echo ${propertiesPath}
if test -f ${propertiesPath}; then
  if test "${2}" != "deploy" ; then
    cd ..
    if test -f ${deployDir}/bin/occ; then
      ${deployDir}/bin/occ shutn group mule
      ${deployDir}/bin/occ shutn group ops
    fi
    if test -d ${deployDir}; then
      rm -rf ${deployDir}
    fi
    mkdir ${deployDir}
    cd ${workdir}

    echo mvn -P ${1} clean package \&\& \
    tar xzvf ${tarPath} -C ${deployDir} \&\& \
    ${deployDir}/bin/occ start group ops \&\& \
    ${deployDir}/bin/occ start group mule 

    mvn -P ${1} clean package && \
    tar xzvf ${tarPath} -C ${deployDir} && \
    ${deployDir}/bin/occ start group ops && \
    ${deployDir}/bin/occ start group mule 
  else
    if test -f ${tarPath}; then
      cd ..
      if test -f ${deployDir}/occ/bin; then
        ${deployDir}/bin/occ shutn group mule
        ${deployDir}/bin/occ shutn group ops
      fi
      if test -d ${deployDir}; then
        rm -rf ${deployDir} 
        mkdir ${deployDir}
      fi
      cd ${workdir}
      tar xzvf ${tarPath} -C ${deployDir} && \
      ${deployDir}/bin/occ start group ops && \
      ${deployDir}/bin/occ start group mule 
    else
      echo "deploy only specified but ${tarPath} does not exist."

    fi
  fi
else
  echo ${propertiesPath} does not exist.
  echo "syntax:" 
  echo "deploy.sh ENVNAME"
  echo Aborting

fi
